﻿using System.Text;
using Micro.Extensions.Utilities;
using Newtonsoft.Json;

namespace Micro.Extensions.Cache.Serializer
{
    public class DefaultJsonSerializer : ICachingSerializer
    {
        private readonly JsonSerializerSettings _jsonSerializerSettings;

        public DefaultJsonSerializer(JsonSerializerSettings settings = null)
        {
            if (settings != null) _jsonSerializerSettings = settings;
            else
            {
                _jsonSerializerSettings = new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    NullValueHandling = NullValueHandling.Ignore
                };
            }
        }

        public byte[] Serialize<T>(T value)
        {
            return Encoding.UTF8.GetBytes(value.ToJson(_jsonSerializerSettings));
        }

        public T Deserialize<T>(byte[] bytes)
        {
            var jsonStr = Encoding.UTF8.GetString(bytes);
            return jsonStr.FromJsonToObj<T>();
        }
    }
}
